package com.spider.silence.pool;

import com.google.common.collect.Lists;
import com.spider.silence.downloader.TianFuForumDownLoader;
import com.spider.silence.utils.PropertiesUtil;

import java.lang.reflect.InvocationTargetException;
import java.util.LinkedList;

/**
 * Created by Administrator on 2016/12/30 0030.
 */
public class TianFuForumDownLoaderPool {
    private static  TianFuForumDownLoaderPool instance=null;
    protected LinkedList<TianFuForumDownLoader> pool = Lists.newLinkedList();

    private   TianFuForumDownLoaderPool(){
        int initNum= Integer.parseInt(PropertiesUtil.getVal("TianFuForum.DownLoader.Pool.initNum"));

        for(int i=0;i<initNum;i++){
                TianFuForumDownLoader downLoader =new TianFuForumDownLoader();
                pool.add( downLoader);
        }
    }

    public  static TianFuForumDownLoaderPool getInstance(){
        if(instance==null){
            instance=new TianFuForumDownLoaderPool();
        }
        return  instance;
    }
    public  void releaseDownLoader(TianFuForumDownLoader downloader) {
        if (downloader != null) {
            synchronized (pool) {
                pool.addLast(downloader);
                pool.notifyAll();
            }
        }
    }

    public  TianFuForumDownLoader fetchDownLoader(long mills) throws InterruptedException {
        synchronized (pool){
            if(mills<=0){
                while (pool.isEmpty()){
                    pool.wait();
                }
                return pool.removeFirst();
            }else {
                long future= System.currentTimeMillis()+mills;
                long remianing=mills;
                while (pool.isEmpty() && remianing >0){
                    pool.wait(remianing);
                    remianing=future-System.currentTimeMillis();
                }
                TianFuForumDownLoader downLoader =null;
                if(!pool.isEmpty()){
                    downLoader=pool.removeFirst();
                }
                return downLoader;
            }
        }
    }

    /**
     * 清空池
     */
    public void empty(){
        pool=Lists.newLinkedList();
    }
}
